package online.flowerinsnow.minecraft.bukkit.manhunt.runnable;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import online.flowerinsnow.minecraft.bukkit.manhunt.Manhunt;

import java.util.HashMap;
import java.util.Map;

public class DamagerRecordRunnable extends BukkitRunnable {
    public Player player;
    public Entity damager;
    public DamagerRecordRunnable(Player player, Entity damager) {
        this.player = player;
        this.damager = damager;
    }
    @Override
    public void run() {
        resetLastDamager(player);
    }
    public DamagerRecordRunnable start() {
        runTaskLater(Manhunt.getInstance(), 200L);
        return this;
    }

    private static final Map<Player, DamagerRecordRunnable> lastDamager = new HashMap<>();
    public synchronized static void setLastDamager(Player player, Entity entity) {
        resetLastDamager(player);
        lastDamager.put(player, new DamagerRecordRunnable(player, entity).start());
    }
    public synchronized static void resetLastDamager(Player player) {
        DamagerRecordRunnable runnable = lastDamager.get(player);
        if (runnable == null) return;
        runnable.cancel();
        lastDamager.remove(player);
    }
    public synchronized static Entity getLastDamager(Player player) {
        DamagerRecordRunnable runnable = lastDamager.get(player);
        return runnable == null ? null : runnable.damager;
    }
}
